//
//  UserAccount.swift
//  weibo
//
//  Created by 上官风雨 on 15/11/10.
//  Copyright © 2015年 上官风雨. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding {
    //用户令牌
    var access_token : String?
    //令牌过期时间
    var expires_date :NSDate?
    
    //令牌的有效时间,单位是秒
    var expires_in : NSTimeInterval = 0 {
        
        didSet{
          
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
            
        }
        
        
    }
    
    //当前用户的id
    var uid : String?
    //用户的头像地址
    var avatar_large : String?
    
    //用户名
    var name : String?
    
    init(dict:[String : AnyObject]) {
        
        super.init()
        
        setValuesForKeysWithDictionary(dict)
        
    }
    //过滤不需要的字段
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
        
    }
    override var description: String {
        let keys = ["access_token","expires_in","uid","avatar_large","name"]
        return dictionaryWithValuesForKeys(keys).description
    }
    
    //归档对象
     func encodeWithCoder(aCoder: NSCoder){
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        
    }
    
    //解归档对象
    required init?(coder aDecoder: NSCoder) {
        
       access_token = aDecoder.decodeObjectForKey("access_token") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
    }
    
    //对外提供归档方法
    func saveAccount(){
        
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
        
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
        print(path)
        
    }
    
    //对外提供一个解归档的类方法
    class func loadAccount() -> UserAccount? {
        
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")

        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount {
            
            return account
        }
        
        return nil
    }
    
    
    

}
